package com.ming.common.beetl.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.ming.common.Options;
import com.ming.common.SortBy;
import com.ming.common.beetl.cache.CacheSqlManagerUtil;
import com.ming.common.beetl.entity.IvyDbDatasource;
import com.ming.common.beetl.entity.IvyDbSqlManager;
import com.ming.common.beetl.util.Result;
import com.ming.common.beetl.util.StrUtil;
import com.ming.common.beetl.vo.IvyDbSqlManagerVo;
import com.ming.common.init.LogInfo;
import com.ming.common.init.LogInit;
import com.ming.common.util.ClassFieldUtil;
import com.ming.common.xxljob.annotation.PermissionLimit;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.page.PageResult;
import org.beetl.sql.core.query.LambdaQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/db/sql/manager")
public class IvyDbSqlManagerController {

    private static final Logger LOG = LoggerFactory.getLogger(IvyDbSqlManagerController.class);

    @Resource
    private SQLManager sqlManager;

    @PostMapping("/option")
    @PermissionLimit(limit = false)
    public Result<?> option(@RequestBody Map<String,Object> map) {
        return Result.OK(ClassFieldUtil.getFieldAnnoDescribe(IvyDbSqlManager.class, map));
    }

    @PostMapping("/options")
    @PermissionLimit(limit = false)
    public Result<?> options(@RequestBody Map<String,Object> map) {
        LambdaQuery<IvyDbSqlManager> query = sqlManager.lambdaQuery(IvyDbSqlManager.class);
        List<IvyDbSqlManager> list = query.select(IvyDbSqlManager::getId,IvyDbSqlManager::getSmBeanName,IvyDbSqlManager::getSmName);
        list = list.stream().peek(m->m.setSmName(m.getSmName()+"【"+m.getSmBeanName()+"】")).collect(Collectors.toList());
        return Result.OK(list);
    }

    @PostMapping("/page")
    @PermissionLimit(limit = false)
    public Result<PageResult<IvyDbSqlManager>> page(@RequestBody IvyDbSqlManagerVo vo){
        LambdaQuery<IvyDbSqlManager> lambdaQuery = sqlManager.lambdaQuery(IvyDbSqlManager.class);
        lambdaQuery.andLike(IvyDbSqlManager::getSmBeanName, LambdaQuery.filterLikeEmpty(vo.getSmBeanName()));
        lambdaQuery.andLike(IvyDbSqlManager::getSmName, LambdaQuery.filterLikeEmpty(vo.getSmName()));
        lambdaQuery.andEq(IvyDbSqlManager::getDatasourceId, LambdaQuery.filterEmpty(vo.getDatasourceId()));
        lambdaQuery.andEq(IvyDbSqlManager::getDisabled, LambdaQuery.filterEmpty(vo.getDisabled()));
        lambdaQuery.andLike(IvyDbSqlManager::getDbStyle, LambdaQuery.filterLikeEmpty(vo.getDbStyle()));
        Options options = vo.getOptions();
        List<SortBy> sortBy = options.getSortBy();
        for (SortBy sort : sortBy) {
            if ("desc".equalsIgnoreCase(sort.getOrder())) {
                lambdaQuery.desc(StrUtil.camelToSnake(sort.getKey()));
            } else {
                lambdaQuery.asc(StrUtil.camelToSnake(sort.getKey()));
            }
        }
        PageResult<IvyDbSqlManager> page = lambdaQuery.page(options.getPage(), options.getItemsPerPage());
        return Result.OK(page);
    }

    @PostMapping("/add")
    @PermissionLimit(limit = false)
    public Result<?> add(@RequestBody IvyDbSqlManager item){
        LambdaQuery<IvyDbSqlManager> lambdaQuery = sqlManager.lambdaQuery(IvyDbSqlManager.class);
        lambdaQuery.andEq(IvyDbSqlManager::getSmBeanName, item.getSmBeanName());
        long count = lambdaQuery.count();
        if(count > 0){
            return Result.error("新增失败：beanName已存在");
        }
        LambdaQuery<IvyDbSqlManager> query = sqlManager.lambdaQuery(IvyDbSqlManager.class);
        if(item.getDisabled() == null){
            item.setDisabled(false);
        }
        handler(item);
        int i = query.insert(item);
        return Result.OK(i);
    }

    @PostMapping("/update")
    @PermissionLimit(limit = false)
    public Result<Object> update(@RequestBody IvyDbSqlManager item){
        LambdaQuery<IvyDbSqlManager> lambdaQuery = sqlManager.lambdaQuery(IvyDbSqlManager.class);
        lambdaQuery.andNotEq(IvyDbSqlManager::getId, item.getId());
        lambdaQuery.andEq(IvyDbSqlManager::getSmBeanName, item.getSmBeanName());
        long count = lambdaQuery.count();
        if(count > 0){
            return Result.error("更新失败：beanName已存在");
        }
        handler(item);
        int i = sqlManager.updateById(item);
        return Result.OK("更新成功", i);
    }

    private void handler(IvyDbSqlManager item){
        if("single".equalsIgnoreCase(item.getType())){
            item.setSlaveDatasourceIds(null);
        }
        String sqlInterceptors = item.getSqlInterceptors();
        if(cn.hutool.core.util.StrUtil.isNotBlank(sqlInterceptors) && sqlInterceptors.startsWith(",")){
            item.setSqlInterceptors(sqlInterceptors.substring(1));
        }
        String slaveDatasourceIds = item.getSlaveDatasourceIds();
        if(cn.hutool.core.util.StrUtil.isNotBlank(slaveDatasourceIds) && slaveDatasourceIds.startsWith(",")){
            item.setSqlInterceptors(slaveDatasourceIds.substring(1));
        }
    }

    @PostMapping("/delete")
    @PermissionLimit(limit = false)
    public Result<Integer> delete(@RequestBody IvyDbSqlManager item){
        LambdaQuery<IvyDbSqlManager> lambdaQuery = sqlManager.lambdaQuery(IvyDbSqlManager.class);
        lambdaQuery.andEq(IvyDbSqlManager::getId, item.getId());
        int i = lambdaQuery.delete();
        return Result.OK("删除成功",i);
    }

    @PostMapping("/exec")
    @PermissionLimit(limit = false)
    public Result<?> exec(@RequestBody IvyDbSqlManagerVo vo){
        String sql = vo.getSourceSql();
        if(cn.hutool.core.util.StrUtil.isBlank(sql)){
            return Result.error("SQL语句不能为空！");
        }
        if(sql.contains("?")){
            return Result.error("SQL参数异常！");
        }
        sql = sql.trim();

        LogInfo logInfo = LogInit.getLogInfo();
        SQLManager manager = null;
        if(StrUtil.isNotEmpty(vo.getSmBeanName())){
            manager = CacheSqlManagerUtil.getCache(vo.getSmBeanName(), SQLManager.class);
        }else {
            manager = CacheSqlManagerUtil.getCache(String.valueOf(vo.getId()), SQLManager.class);
        }
        if(sql.toLowerCase().startsWith("select")){
            List<Map> returnVal = manager.execute(new SQLReady(sql), Map.class);
            return Result.OK(LogInit.getResultVal(returnVal,logInfo));
        }else{
            int returnVal = manager.executeUpdate(new SQLReady(sql));
            return Result.OK(LogInit.getResultVal(returnVal,logInfo));
        }
    }
}
